package com.dongdongshop.shiro;

import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbPerson;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.PersonService;
import com.dongdongshop.service.SellerService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.servlet.http.HttpServletRequest;

public class LoginRealm extends AuthorizingRealm {

    @DubboReference
    private SellerService sellerService;

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证方法(登录方法)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;

        //从token中获取用户名
        String sellerId = token.getUsername();

        TbSeller login = sellerService.getInfo(sellerId);
        if (login == null){
            return null;
        }

        //如果审核未通过（自定义异常）
        if (!login.getStatus().equals("1")){
            throw new LoginException("审核未通过");
        }

        //1.表示登录后的对象 2.数据库中的密码 3.盐 4.用户的真实姓名
        return new SimpleAuthenticationInfo(login,login.getPassword(), ByteSource.Util.bytes(login.getSalt()),login.getName());
    }
}
